//
//  PasswordSetView.swift
//  KoiAccounting
//
//  Created by 纪洪文 on 13.04.25.
//

import SwiftUI

struct PasswordSetView: View {
    @Environment(\.presentationMode) var presentationMode;
    @Environment(\.presentToast) var presentToast
    
    @State var password = ""
    @State var passwordConfirm = ""
    
    @StateObject var viewModel = PasswordSetViewModel()
    
    var body: some View {
        VStack {
            Text("6~16位密码，同时包含字母和数字")
                .font(.system(size: 13))
                .foregroundColor(Color.koiColorTitleSecond)
                .padding(.vertical, 16)
            
            SecureField("请输入密码", text: $password)
                .padding(EdgeInsets(top: 16, leading: 25, bottom: 16, trailing: 25))
                .background(Color.koiColorBackgroundItem)
                .cornerRadius(40)
                .keyboardType(.numberPad)
                .frame(width: 272)
            
            SecureField("请再次输入密码", text: $passwordConfirm)
                .padding(EdgeInsets(top: 16, leading: 25, bottom: 16, trailing: 25))
                .background(Color.koiColorBackgroundItem)
                .cornerRadius(40)
                .keyboardType(.numberPad)
                .frame(width: 272)
            
            Button(action:onSureClick) {
                Text("完成")
                    .font(.system(size: 16))
                    .bold()
                    .padding(EdgeInsets(top: 16, leading: 0, bottom: 16, trailing: 0))
                    .frame(width: 272)
                    .foregroundColor(Color.white)
                    .background(Color.koiColorPrimary)
                    .cornerRadius(40)
                    .padding(.top, 20)
            }
            
            Spacer()
        }
        .toolbar{
            ToolbarItem(placement: .navigationBarLeading) {
                Button (action:{
                    presentationMode.wrappedValue.dismiss()
                }) {
                    Image(systemName: "chevron.left").foregroundColor(Color.koiColorTitle)
                }
            }
        }
        .navigationBarTitle(Text("设置密码"), displayMode: .inline)
        .navigationBarBackButtonHidden()
        .onChange(of: viewModel.state) { value in
            if value == "" {
                return
            }
            if value == "success" {
                presentToast(.init(message: "设置成功"))
                presentationMode.wrappedValue.dismiss()
            } else {
                presentToast(.init(message: value))
            }
            viewModel.state = ""
        }
    }
    
    private func onSureClick() {
        if password != passwordConfirm {
            presentToast(.init(message: "两次输入的密码不一致"))
            return
        }
        viewModel.passwordSet(password: password)
    }
}

#Preview {
    PasswordSetView()
}
